package com.wenda.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wenda.admin.entity.TbUser;
import com.wenda.admin.mapper.UserMapper;
import com.wenda.admin.vo.Resp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @RequestMapping("index")
    public String index(Model model){
        QueryWrapper<TbUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status",2000);
        queryWrapper.orderByDesc("modify_time");
        model.addAttribute("dataList", userMapper.selectList(queryWrapper));
        return "/user/index";
    }

    @RequestMapping("addIndex")
    public String addIndex(){
        return "/user/add";
    }

    @RequestMapping("add")
    public String add(Model model,TbUser obj){
        Date now = new Date();
        obj.setCreateTime(now);
        obj.setModifyTime(now);
        obj.setUserType("普通管理员");
        obj.setStatus(2000);
        userMapper.insert(obj);
        return index(model);
    }

    @RequestMapping("del")
    public String del(String id,Model model){
        TbUser staff = userMapper.selectById(id);
        staff.setModifyTime(new Date());
        staff.setStatus(-1);
        userMapper.updateById(staff);
        return index(model);
    }

    @RequestMapping("editIndex")
    public String editIndex(String id,Model model){
        TbUser staff = userMapper.selectById(id);
        model.addAttribute("obj",staff);
        return "/user/edit";
    }

    @RequestMapping("edit")
    public String edit(Model model,TbUser obj){
        obj.setModifyTime(new Date());
        userMapper.updateById(obj);
        return index(model);
    }

    @RequestMapping("resetPwd")
    @ResponseBody
    public Resp resetPwd(String id){
        TbUser user = userMapper.selectById(id);
        if(user.getUserType().equals("超级管理员")){
            return Resp.success("无法重置超级管理员的密码");
        }else{
            user.setPassword("123456");
            return Resp.success("用户：【" + user.getUserName() + "】的密码被成功重置为：123456");
        }
    }
}
